
const Controller = require('../../core/Controller');
const query = require('../../core/db');


class couponController extends Controller {
  constructor() {
    super();
  }
  async getCouponList(ctx) {
    let sql = 'select * from coupon where 1=1';
    let values = [];
    ctx.response.body = await query(sql, values).then( results => { return results; });
  }

  async updateCoupon(ctx) {
    const {c_id = '', c_name = '', c_amount = '', c_getTimeType = '', c_url = '', c_remark = ''} = ctx.request.body || ctx.request.query;
    //console.log(qurey);
    if(c_id.length) {
      let zhanwei = [], values = [];
      if(c_name.length > 0) {
        zhanwei.push('c_name=?');values.push(c_name);
      }
      if(c_amount.length > 0) {
        zhanwei.push('c_amount=?');values.push(c_amount);
      }
      if(c_getTimeType.length > 0) {
        zhanwei.push('c_getTimeType=?');values.push(c_getTimeType);
      }
      if(c_url.length > 0) {
        zhanwei.push('c_url=?');values.push(c_url);
      }
      if(c_remark.length > 0) {
        zhanwei.push('c_remark=?');values.push(c_remark);
      }
      let where = 'where c_id=?';
      values.push(c_id);
      let sql = `update coupon set ${zhanwei.join()} ${where}`;
      //console.log('sql', sql);
      //console.log('values', values);
      let coupon = await query(sql, values).then( results => { return results; });
      console.log('palace', coupon);
      ctx.response.body = {
        succ: true,
        mess: {
          c_name,
          c_amount,
          c_getTimeType,
          c_url,
          c_remark
        }
      };
    } else {
      ctx.response.body = {
        succ: false,
        mess: 'c_id is not exist'
      };
    }
  }

  async addCoupon(ctx) {
    const { c_name = '', c_amount = '', c_getTimeType = '', c_url = '', c_remark = '' } = ctx.request.body || ctx.request.query;

    let values = [c_name, c_amount, c_getTimeType, c_url, c_remark];
    console.log('values', values);
    let sql = `INSERT INTO coupon (c_name,c_amount,c_getTimeType,c_url,c_remark) VALUES (?,?,?,?,?)`;
    let coupon = await query(sql, values).then( results => { return results; });
    console.log('coupon', coupon);
    ctx.response.body = {
      succ: true,
      mess: {
        c_name,
        c_amount,
        c_getTimeType,
        c_url,
        c_remark
      }
    };
  }

}

module.exports = new couponController;
